/**
 * 21. 合并两个有序链表
 * https://leetcode-cn.com/problems/merge-two-sorted-lists/
 */
public class Solutions_21 {
    public static void main(String[] args) {
        int[] arr1 = {1, 2, 4};
        int[] arr2 = {1, 3, 4};  // output: {1, 1, 2, 3, 4, 4}

        ListNode l1 = MyLinkedListUtils.ArrayToListNode(arr1);
        ListNode l2 = MyLinkedListUtils.ArrayToListNode(arr2);

        ListNode result = mergeTwoLists(l1, l2);
        System.out.println(MyLinkedListUtils.ListNodeToString(result));
    }

    public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        // 判断空值
        if (l1 == null || l2 == null) {
            return l1 == null ? l2 : l1;
        }
        ListNode head = new ListNode(-1);
        ListNode cur = head;

        while (l1 != null && l2 != null) {
            // 比较得到最小值
            if (l1.val < l2.val) {
                cur.next = l1;
                l1 = l1.next;
            } else {
                cur.next = l2;
                l2 = l2.next;
            }
            cur = cur.next;
        }
        if (l1 == null || l2 == null) {
            // 不为空的链接直接作为 cur 的下一节点
            cur.next = l1 == null ? l2 : l1;
        }
        return head.next;
    }
}
